#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<conio.h>
#include<windows.h>
#include"Xac_Dinh_Huong.cpp"
#include"gotoxy.cpp"
#include"tuong1.cpp"
#include"tuong2.cpp"

typedef struct ChuRanVuiVe
{
	int x;
	int y;
};

bool Random(int u, int v, int n, ChuRanVuiVe a[])
{
	for(int i=0;i<n;i++)
		if(a[i].x==u&&a[i].y==v)
			return false;
	return true;
}

void Dich_chuyen(short Huong, ChuRanVuiVe a[], int i)
{
	if (Huong==1) a[i].y-=1;
	else if (Huong==2) a[i].x-=1;
	else if (Huong==3) a[i].x+=1;
	else if (Huong==0) a[i].y+=1;
}

bool Kiem_tra(int n, ChuRanVuiVe a[])
{
	for(int i=2;i<n;i++)
		if(a[0].x==a[i].x&&a[0].y==a[i].y)
			return false;
	return true;
}

main()
{
	ChuRanVuiVe a[200];
	int n=3;
	int i,j;
	char b[100][100];
	srand(time(NULL));
	printf("Nhan 1 phim bat ki de bat dau: ");
	while(1)
		if(kbhit())
			break;
	tuong1(b);
	printf("\n\n\n");
	tuong2(b);
	short Level=1;
	gotoxy(27,30);
	printf("Diem la: %d\n\t\t\t    Level: %d",n-3,Level);
	a[0].x=26;
	a[0].y=9;
	gotoxy(0,0);
	printf("\t\t\t\t");
	short Huong=3,Huong1;
	unsigned char c;
	int u,v;
	short e=224;
	short d=220;
	do
	{
		u=rand()%23+21;
		v=rand()%23+4;
	}
	while(Random(u,v,n,a)==false);
	gotoxy(u,v);
	printf("%c",36);
	if(kbhit())
	{
		c = getch();
		if (c==224)
		{
			c = getch();
			if (c==72) Huong=1;//lên;
			if (c==75) Huong=2;//trái;
			if (c==77) Huong=3;//phai;
			if (c==80) Huong=0;//xuông;
		}
	}
	do
	{
		Sleep(d);
		if (kbhit())
		{
			c = getch();
			if (c==224)
			{
				c = getch();
				Xac_dinh_huong(c,Huong1,Huong);
			}
		}
		gotoxy(a[n-1].x,a[n-1].y);
		printf(" ");
		gotoxy(a[0].x,a[0].y);
		printf(" ");
		Dich_chuyen(Huong,a,0);
		for(i=n-1;i>0;i--)
		{
			a[i].x=a[i-1].x;
			a[i].y=a[i-1].y;
			gotoxy(a[i].x,a[i].y);
			printf("%c",3);
		}
		gotoxy(a[0].x,a[0].y);
		printf("%c",1);
		if(a[0].x==u&&a[0].y==v)
		{
			gotoxy(u,v);
			printf(" ");
			n++;
			do
			{
				u=rand()%23+21;
				v=rand()%23+4;
			}
			while(Random(u,v,n,a)==false);
			gotoxy(u,v);
			printf("%c",36);
			Dich_chuyen(Huong,a,n-1);
			gotoxy(27,30);
			if((n-3)%5==0)
			{
				d-=10;
				Level++;
			}
			printf("Diem la: %d\n\t\t\t    Level: %d",n-3,Level);
		}
		Huong1=Huong;
	}
	while(c!=27&&a[0].x!=44&&a[0].y!=27&&a[0].x!=20&&a[0].y!=3&&Kiem_tra(n,a)==true);
	gotoxy(27,32);
	printf("You lose.\n"); 
}